/**
 * 获取所有科研题目列表
 * 
 * 这是行政和教研老师通用的接口
 * 
 * /general/topic/getlist
 */

  
const Topics= require('../../../models/researchTopics')
const utils = require('../../../utils/index')
const $ = require('../../../utils/common')

const get_topic_list = async function (req, res) {
    try {

        var topic_list
        var offset = 1
        var limit = parseInt(req.query.size)
        if (req.query.page > 1) {
            offset = parseInt(req.query.size) * (parseInt(req.query.page) - 1)
        } 
        else if (req.query.page == 1) {
            offset = 0
        }
        
        if (!req.query.year_id) {
            topic_list = await Topics.findAndCountAll({
                offset: offset,
                limit: limit,
                order: [
                    ['createdAt', 'DESC'],
                ],
            })
        }

        else if (req.query.year_id) {
            const year = req.query.year_id
            topic_list = await Topics.findAndCountAll({
                offset: offset,
                limit: limit,
                order: [
                    ['createdAt', 'DESC'],
                ],
                where: {
                    years: year
                }
            })
        }

        if (topic_list == null) {
            $.sendMessage(res, 1015, '无效相关数据')
            return
        }

        res.json({
            code: 200,
            message: '获取成功',
            data: topic_list
        })
           
        // 日志
        utils.create_a_log(req, '科研题目管理', '浏览课题列表')
    }
    catch(error) {
        res.json({
            message: "抓到异常",
            error: 'error' + error
        })
        utils.create_a_log(req, '科研题目管理', '浏览课题列表', '失败')
        return
    } 
}
    
module.exports = get_topic_list